package com.jv.douyin;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.VideoView;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    final String TAG = "main";
    private Button btn_play;
    private VideoView videoplay;
    //    private MediaPlayer player;
    private MediaController mediaController;

    String url = "";
    String title = "";
    String image = "";
    private Button downloadBtn;
    private Button getvideoBtn;
    private EditText urlEdittext;
    private ProgressBar progress;

    // https://api.spapi.cn/get?appkey=edec16cb300f7c7a7c6ce230edd26144&url=https://v.douyin.com/JBxUrdN/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initWidget();
        initListenr();
    }

    void initWidget() {
        btn_play = findViewById(R.id.play);
        videoplay = findViewById(R.id.videoplay);
//        player = MediaPlayer.create(this, R.raw.download);
        mediaController = new MediaController(this);
        downloadBtn = findViewById(R.id.download);
        urlEdittext = findViewById(R.id.urledittext);
        getvideoBtn = findViewById(R.id.getvideo);
        progress = findViewById(R.id.progress);
    }

    void initListenr() {
        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaController.setMediaPlayer(videoplay);
                videoplay.setMediaController(mediaController);
//                videoplay.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.download));
                if (!url.equals("")) {
                    videoplay.setVideoURI(Uri.parse(url));
                    videoplay.start();
                } else {
                    Toast.makeText(MainActivity.this, "你还没有获取视频,请解析后再试", Toast.LENGTH_SHORT).show();
                }
            }
        });
        downloadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!url.equals("")) {
                    // 这里进行下载操作
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            downloadFile();
                        }
                    }).start();
                } else {
                    // 3857805bd0eb58508e29ebc5883dd320
                    Toast.makeText(MainActivity.this, "你还没有获取视频视频,请稍后再试", Toast.LENGTH_SHORT).show();
                }
            }
        });
        getvideoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String res =  new OkHttpClient().newCall(new Request.Builder().url(genImplement(urlEdittext.getText().toString())).build()).execute().body().string();
                            Log.e(TAG,res);
                            JSONObject outJson = null;
                            try {
                                outJson = JSONObject.parseObject(res);
                            } catch (Exception e) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this, "请稍后再试", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                return;
                            }
                            switch (outJson.getIntValue("status")) {
                                case 101:
                                    title = outJson.getJSONObject("data").getString("title");
                                    image = outJson.getJSONObject("data").getString("image");
                                    url = outJson.getJSONObject("data").getString("url");
//                                    downloadFile();
                                    break;
                                case 102:
                                    url = "";
                                    break;
                                default:

                            }
                        } catch (IOException e) {
                            // 在这里写获取失败
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    public String genImplement(String url) {
        String a = "/";
        String b = "i.c";
        String c = ":";
        String d = "tps";
        String e = "app";
        String f = "key";
        String g = ".";
        return "ht" + d + c + a + a + "api" + g + "spap" + b + "n" + a + "get" + "?" + e + f + "="
//                + "edec16cb300f7c7a7c6ce230edd26144&url=" + url;
                + "3857805bd0eb58508e29ebc5883dd320&url=" + url;
        // https://api.spapi.cn/get?appkey=3857805bd0eb58508e29ebc5883dd320&url=https://v.douyin.com/JBxUrdN/
    }

    /**
     * 下载文件,文件的地址时url,这个方法必须在线程调用
     */
    void downloadFile() {
        if (url.equals(""))
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
                }
            });
        else {
            final long startTime = System.currentTimeMillis();
            Log.i(TAG, "startTime=" + startTime);
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Connection", "close")
                    .build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, "download failed");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    // 储存下载文件的目录
                    try {
                        is = response.body().byteStream();
                        long total = response.body().contentLength();
                        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/AJv");
                        if (!file.exists())
                            file.mkdirs();
                        fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/AJv/" + System.currentTimeMillis() + ".mp4");
                        long sum = 0;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            sum += len;
                            int mProgress = (int) (sum * 1.0f / total * 100);
//                            Log.e(TAG, "download progress : " + progress);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.setProgress(mProgress);
                                }
                            });
                            Log.e(TAG, String.valueOf(mProgress));
                        }
                        fos.flush();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                            }
                        });
                        Log.e(TAG, "totalTime=" + (System.currentTimeMillis() - startTime));
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e(TAG, "download failed : " + e.getMessage());
                    } finally {
                        try {
                            if (is != null)
                                is.close();
                        } catch (IOException e) {
                        }
                        try {
                            if (fos != null)
                                fos.close();
                        } catch (IOException e) {
                        }
                    }
                }
            });
        }
    }
}


//
// {
//    "status":101,
//    "msg":"获取成功",
//    "data":{
//        "title":"钟南山获授共和国勋章！实至名归，点赞致敬！",
//         "image":"https://p3.douyinpic.com/tos-cn-p-0015/bad05ae7b5804ec4aae90639ee95ce71_1599532248~tplv-dy-360p.jpeg?from=4257465056&s=&se=false&sh=&sc=&l=202109031232590102121641634D04AD82&biz_tag=feed_cover","video":"http://v3-dy.ixigua.com/d782e7854e7f932b8c3109bc81b61c98/6131b39c/video/tos/cn/tos-cn-ve-15/e2fb1a4be732416491a4e6de3230d949/?a=1128&br=951&bt=951&cd=0%7C0%7C0&ch=0&cr=0&cs=0&cv=1&dr=0&ds=3&er=&ft=XEy-Iqq3mw3PSYITz7VFAYiUfTusIvkMWy&l=202109031232590102120631590A39A4AD&lr=&mime_type=video_mp4&net=0&pl=0&qs=0&rc=amk2NnY4aGVodzMzO2kzM0ApZTo7M2k2ZTtnNzg6Zjo6Z2dkNS8yLWhfbV9fLS01LTBzc2E1Xl9fXzAyXjRiXzRfNi46Yw%3D%3D&vl=&vr=",
//         "url":"http://v3-dy.ixigua.com/d782e7854e7f932b8c3109bc81b61c98/6131b39c/video/tos/cn/tos-cn-ve-15/e2fb1a4be732416491a4e6de3230d949/?a=1128&br=951&bt=951&cd=0%7C0%7C0&ch=0&cr=0&cs=0&cv=1&dr=0&ds=3&er=&ft=XEy-Iqq3mw3PSYITz7VFAYiUfTusIvkMWy&l=202109031232590102120631590A39A4AD&lr=&mime_type=video_mp4&net=0&pl=0&qs=0&rc=amk2NnY4aGVodzMzO2kzM0ApZTo7M2k2ZTtnNzg6Zjo6Z2dkNS8yLWhfbV9fLS01LTBzc2E1Xl9fXzAyXjRiXzRfNi46Yw%3D%3D&vl=&vr="
//    }
// }
//
